import React, {useEffect, useState} from 'react';
import {makeStyles} from "@material-ui/core";
import TextField from "@material-ui/core/TextField";
import Paper from "@material-ui/core/Paper";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import {useHistory} from "react-router-dom";
import {useAuth} from "../contexts/AuthContext";
import Alert from '@material-ui/lab/Alert';
import CircularProgress from "@material-ui/core/CircularProgress";
import Validator from 'validator'
import {anonymousInstance} from "../api";

const useStyles = makeStyles(theme => ({
    paper: {
        maxWidth: "550px",
        margin: "auto",
        marginTop: theme.spacing(10)
    },
    form: {
        '& > *': {
            width: "100%",
            marginBottom: theme.spacing(1),
            marginTop: theme.spacing(3),
        }
    },
    header: {
        textAlign: "center",
        marginBottom: theme.spacing(6),
    },
    alert: {
        marginBottom: theme.spacing(3),
    }
}))

const ResetPassword = () => {
    const classes = useStyles()
    const history = useHistory()
    const [loading, setLoading] = useState(false)
    const [errors, setErrors] = useState({})
    const [email, setEmail] = useState('')
    const {isAuthenticated} = useAuth()

    // 如果已经登录不让她访问这个页面
    useEffect(() => {
        if (isAuthenticated)
            history.push('/')
    }, [isAuthenticated, history])

    // 前端校验
    const validate = ({email}) => {
        const errors = {}
        if (!email) errors.email = '邮箱不能为空'
        if (email && !Validator.isEmail(email)) errors.email = '无效邮箱'
        return errors
    }

    const handleSubmit = async (e) => {
        e.preventDefault()

        try {
            setErrors({})
            setLoading(true)

            // 数据校验
            const errors = validate({email})
            if (Object.keys(errors).length !== 0) {
                setErrors(prevState => ({...prevState, ...errors}))
                setLoading(false)
            } else {
                await anonymousInstance.post('/users/reset_password/', {email})
                setLoading(false)
                history.push('/reset_password/done')
            }

            // 可以注释掉前面代码，检验后端校验是否有效
            // await instance.post('users/reset_password/', {email})
            setLoading(false)
        } catch (e) {
            setLoading(false)

            // 后端校验产生的错误信息
            if (e.response && e.response.status === 400) {
                const data = e.response.data
                // 如果输入为空
                if (data.hasOwnProperty('email'))
                    setErrors(data)
                else
                    // 如果后端数据库中不存在该用户
                    setErrors({'detail': `“${email}”用户不存在`})
            } else {
                setErrors({detail: '邮件发送失败！服务器错误,管理员正在解决...'})
            }
        }
    }

    return (
        <Paper className={classes.paper} elevation={0}>

            {loading && <CircularProgress/>}

            <Typography variant="h3" className={classes.header}>输入账号</Typography>

            {errors.detail && (
                <Alert severity="error" className={classes.alert}>{errors.detail}</Alert>
            )}

            <Typography variant="subtitle2">
                请输入要重置密码的邮箱账号
            </Typography>

            <form noValidate className={classes.form} onSubmit={handleSubmit}>
                <TextField
                    error={!!errors.email}
                    label="邮箱"
                    variant="outlined"
                    name="email"
                    type="email"
                    onChange={e => {
                        setErrors(prevState => ({...prevState, email: ''}))
                        setEmail(e.target.value)
                    }}
                    helperText={!!errors.email && errors.email}
                />

                <Button variant="contained" color="primary" size="large" type="submit">
                    下一步
                </Button>
            </form>
        </Paper>
    );
};

export default ResetPassword;